package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.mapper.MemberMapper;
import com.itheima.mapper.OrderMapper;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.vo.OrderVO;
import com.itheima.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private MemberMapper memberMapper;

    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult page(QueryPageBean queryPageBean) {
        // 判断条件是否为空
        if(queryPageBean.getQueryString() == null) queryPageBean.setQueryString("");
        if(queryPageBean.getCurrentPage() == null) queryPageBean.setCurrentPage(1);
        if(queryPageBean.getPageSize() == null) queryPageBean.setPageSize(10);

        // 获取预约订单集合
        List<Order> orders = orderMapper.selectByQueryString(queryPageBean.getQueryString());
        // 根据会员id获取会员信息：姓名、手机号
        ArrayList<OrderVO> orderVOS = new ArrayList<>();
        orders.forEach(order -> {
            // 获取会员信息
            Member member = memberMapper.selectMemberByMemberId(order.getMemberId());
            orderVOS.add(
                    new OrderVO(
                            order.getOrderType(),
                            member.getPhoneNumber(),
                            member.getName(),
                            order.getOrderStatus(),
                            order.getId(),
                            order.getOrderDate()
                    )
            );
        });
        //TODO 开始分页查询 为什么不能用Page<>
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
//        Page<OrderVO> pages = (Page<OrderVO>) orderVOS;
        PageInfo<OrderVO> pageInfo = new PageInfo<>(orderVOS);
//        return new PageResult(pages.getTotal(), pages.getResult());
        return new PageResult(pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * 修改预约信息
     * @param order
     */
    @Override
    public void update(Order order) {
        orderMapper.update(order);
    }
}
